﻿$(function () {
    $('body').CreateController({
        appEvents: {
            'bind:cart': 'bind',
        },
        events: {
            '[data-type="minus"] click': 'Minus',
            '[data-type="add"] click': 'Add',
            '[data-type="input"] keyup': 'InputCheck',
            '[data-type="input1"] keyup': 'InputCheck1',
            '[data-type="input"] afterpaste': 'InputCheck2',
            '[data-type="del"] click': 'Del',
            '[data-type="delproducts"] click': 'DelMore',
            '[data-type="AddWishs"] click': 'AddWishs',
            '[data-type="AddPlusInput"] keyup': 'AddPlus',
            '.pop_arrow_l a click': 'MoveLeft',
            '.pop_arrow_r a click': 'MoveRight',
            '[data-type="AddPlusAdd"] click': 'AddPlusAdd',
            '[data-type="AddPlusMinus"] click': 'AddPlusMinus',
            '[BoxType="g"] click': 'GiftSelect',
            '[BoxType="h"] click': 'AddPlusSelect',
            '[BoxType="p"] click': 'SelectProduct',
            '[BoxType="a"] click': 'SelectAll',
            '[data-type="ganda"] click': 'AlertAddPlusOrGift',
            '[data-type="AddPlusCannel"] click': 'HideAddPlus',
            '[data-type="GiftCannel"] click': 'HideGift',
            '[selectType="AddPlusBtnOk"] click': 'InsertAddPlus',
            '[selectType="GiftBtnOk"] click': 'InsertGift',
            '[data-type="Pay"] click': 'Pay',
            '[data-type="coudan"] click': 'Coudan',
            '[data-type="CancelCoudan"] click': 'HideCoudan',
            '[data-type="ConfirmCoudan"] click': 'AddCoudan',
            '[data-type="couMinus"] click': 'CoudanMinus',
            '[data-type="couAdd"] click': 'CoudanAdd',
            '[data-type="cdLeft"] click': 'CoudanLeft',
            '[data-type="cdRight"] click': 'CoudanRight',
            '[data-type="ChildClose"] click': 'HideChildTan',
            '.pop_select a click': 'ChildSelect',
            '[data-type="SelectSplitOrder"] click': 'SelectOkChildTan',
        },
        bind: function () {
            $("#min_all").html('');
            $.BENLAI.tmpl({ dom: $("#min_all"), v: BENLAI.Model.CartTemp.CartTemps, datas: BENLAI.Model.CartModels });
        },
        Minus: function (t, event) {
            var type = $(t).attr("data-producttype");
            var product = $(t).attr("data-productid");
            var check = $('[data-producttype="' + type + '"][data-productid="' + product + '"][type="checkbox"]').attr("checked") ? 1 : 0;
            var count = $(t).parent().parent().find('[data-type="input"]').attr('data-productvalue');
            var message = "您确定要删除该商品吗？";
            if (type == 1) message = "您确定要删除该组合吗？";
            if ((count - 1) <= 0) {
                if (!confirm(message)) {
                    return false;
                }
            }
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/AddShoppingCart',
                data: {
                    products: product + ',-1,' + type + "," + check,
                    Source: 'cart'
                },
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            $.App.trigger('bind:cart');
                            uptRightCart(result.data);
                        } else {
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        Add: function (t, event) {
            var type = $(t).attr("data-producttype");
            var product = $(t).attr("data-productid");
            var check = $('[data-producttype="' + type + '"][data-productid="' + product + '"][type="checkbox"]').attr("checked") ? 1 : 0;
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/AddShoppingCart',
                data: {
                    products: product + ',1,' + type + "," + check,
                    Source: 'cart'
                },
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            if (result.errorlist) {
                                ShowCartMessage(result.errorlist);
                            }
                            $.App.trigger('bind:cart');
                            uptRightCart(result.data);
                        } else {
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        Del: function (t, event) {
            var type = $(t).attr("data-producttype");
            var product = $(t).attr("data-productid");
            var message = "您确定要删除该商品吗？";
            if (type == 1) message = "您确定要删除该组合吗？";
            if (!confirm(message)) {
                return false;
            }
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/DeleteCart',
                data: {
                    sysNo: product,
                    type: type,
                    Source: 'cart'
                },
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            $.App.trigger('bind:cart');
                            uptRightCart(result.data);
                        } else {
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        DelMore: function (t, event) {
            var message = "您确定要删除选中的商品吗？";
            if (!confirm(message)) {
                return false;
            }
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/DeleteCarts',
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            $.App.trigger('bind:cart');
                            uptRightCart(result.data);
                        } else {
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        AddWishs: function (t, event) {
            var id = $(t).attr('productsysno');
            $.BENLAI.ajax({
                type: "POST",
                cache: false,
                url: "/Products/AddWish/" + id,
                dataType: "json",
                success: function (result) {
                    if (AjaxValidate(result.msg)) {
                        if (result.status == -1) {
                            alert("您未登陆，请先登陆");
                        } else {
                            ShowWishMessage(result);
                        }
                    }
                },
                error: function () {
                    alert("添加失败，请重试");
                }
            });
        },
        InputCheck: function (t, event) {
            var type = $(t).attr("data-producttype");
            var product = $(t).attr("data-productid");
            var count = $(t).attr("data-productvalue");
            var check = $('[data-producttype="' + type + '"][data-productid="' + product + '"][type="checkbox"]').attr("checked") ? 1 : 0;
            t.value = t.value.replace(/\D/g, '');
            var NowCount = $(t).val();
            if (NowCount <= 0 || !Number(NowCount)) {
                $(t).val(count);
                $(t).focus();
                return false;
            }
            $(t).focus();
            if (NowCount == count) {
                return false;
            }
            var addCount = NowCount - count;
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/AddShoppingCart',
                data: {
                    products: product + ',' + addCount + ',' + type + "," + check,
                    Source: 'cart'
                },
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            if (result.errorlist) {
                                ShowCartMessage(result.errorlist);
                            }
                            $.App.trigger('bind:cart');
                        } else {
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        InputCheck1: function (t, event) {
            t.value = t.value.replace(/\D/g, "1");
            if (t.value > 99)
                t.value = 99;
            this.CoudanTotal();
        },
        InputCheck2: function (t, event) {
            t.value = t.value.replace(/\D/g, '');
        },
        MoveLeft: function (t, event) {
            var dl = $('[data-type="AddPlusProducts"]');
            var i = $('[data-type="AppPlusStart"]');
            var n = Number(i.attr("start"));
            if (n <= 0) {
                $('[data-type="AppPlusMoveLeft"]').hide();
                return false;
            }
            n = n - 1;
            i.attr("start", n);
            dl.each(function (k, v) {
                var no = $(v).attr('data-no');
                if (no >= n && no < (n + 4)) {
                    $(v).show();
                } else {
                    $(v).hide();
                }
            });
            if (n > 0 && dl.length > 4) {
                $('[data-type="AppPlusMoveLeft"]').show();
            } else if (n == 0) {
                $('[data-type="AppPlusMoveLeft"]').hide();
            }
            if (n + 4 == dl.length) {
                $('[data-type="AppPlusMoveRight"]').hide();
            } else if (dl.length > 4) {
                $('[data-type="AppPlusMoveRight"]').show();
            }
        },
        MoveRight: function (t, event) {
            var dl = $('[data-type="AddPlusProducts"]');
            var i = $('[data-type="AppPlusStart"]');
            var n = Number(i.attr("start"));
            if (n >= dl.length) {
                $('[data-type="AppPlusMoveRight"]').hide();
                return false;
            }
            n = n + 1;
            i.attr("start", n);
            dl.each(function (k, v) {
                var no = $(v).attr('data-no');
                if (no >= n && no < (n + 4)) {
                    $(v).show();
                } else {
                    $(v).hide();
                }
            });
            if (n > 0 && dl.length > 4) {
                $('[data-type="AppPlusMoveLeft"]').show();
            } else if (n == 0) {
                $('[data-type="AppPlusMoveLeft"]').hide();
            }
            if (n + 4 == dl.length) {
                $('[data-type="AppPlusMoveRight"]').hide();
            } else if (dl.length > 4) {
                $('[data-type="AppPlusMoveRight"]').show();
            }
        },
        GiftSelect: function (t, event) {
            $('[BoxType="g"]').attr('checked', false);
            $(t).attr("checked", true);
        },
        AddPlusSelect: function (t, event) {
            var checked = $(t).attr("checked");
            $('[BoxType="h"]').attr('checked', false);
            $(t).attr("checked", checked);
            this.AddPlusNumAndAmtShow();
        },
        AddPlusAdd: function (t, event) {
            var input = $(t).parent().parent().find('[data-type="AddPlusInput"]');
            var qty = Number(input.val()) + 1;
            $('[data-type="AddPlusInput"]').val(0);
            input.val(qty);
            this.AddPlusNumAndAmtShow();
        },
        AddPlusMinus: function (t, event) {
            var input = $(t).parent().parent().find('[data-type="AddPlusInput"]');
            var qty = Number(input.val()) - 1;
            if (qty < 0) qty = 0;
            $('[data-type="AddPlusInput"]').val(0);
            input.val(qty);
            this.AddPlusNumAndAmtShow();
        },
        AddPlus: function (t, event) {
            var qty = $(t).val();
            $('[data-type="AddPlusInput"]').val(0);
            $(t).val(qty);
            this.AddPlusNumAndAmtShow();
        },
        AddPlusNumAndAmtShow: function (t, event) {
            var addPlus = $('[data-type="AddPlusInput"]');
            var price = 0;
            var qty = 0;
            if (addPlus.length > 0) {
                addPlus.each(function (k, v) {
                    if ($(v).val() > 0) {
                        price = $(v).attr("Price");
                        qty = $(v).val();
                    }
                });
            } else {
                addPlus = $('[BoxType="h"]:checked');
                if (addPlus.length > 0) {
                    price = addPlus.attr("Price");
                    qty = 1;
                }
            }
            price = parseFloat(price * qty).toFixed(2);
            $('[data-type="ShowAddPlusNum"]').html(qty);
            $('[data-type="ShowAddPlusAmt"]').html("￥" + price);
        },
        SelectProduct: function (t, event) {
            var productid = $(t).attr("data-productid");
            var producttype = $(t).attr("data-producttype");
            var productcheck = $(t).attr("checked") ? 1 : 0;
            var productInfo = productid + "," + producttype + "," + productcheck;
            this.UpdateProductCheck(productInfo);
        },
        SelectAll: function (t, event) {
            var check = $(t).attr("checked");
            $('[BoxType="a"]').attr("checked", check);
            $('[BoxType="p"]').attr("checked", check);
            var ProductList = $('[BoxType="p"]');
            var ProductInfo = "";
            $.each(ProductList, function (key, v) {
                if (key != 0) ProductInfo += "|";
                var productcheck = $(v).attr("checked") ? 1 : 0;
                ProductInfo += $(v).attr("data-productid") + "," + $(v).attr("data-producttype") + "," + productcheck;
            });
            this.UpdateProductCheck(ProductInfo);
        },
        UpdateProductCheck: function (product) {
            if (product) {
                $.BENLAI.ajax({
                    type: 'POST',
                    url: '/Cart/CheckProduct',
                    data: {
                        ProductSysNo: product
                    },
                    cache: false,
                    success: function (result) {
                        if (AjaxValidate(result)) {
                            if (result.Status == 0) {
                                BENLAI.Model.CartModels = result.data;
                                $.App.trigger('bind:cart');
                                uptRightCart(result.data)
                            } else {
                                alert(result.Msg);
                            }
                        }
                    }
                });
            }
        },
        AlertAddPlusOrGift: function (t, event) {
            var type = $(t).attr("Promotion-Type");
            var num = $(t).attr("Promotion-Num");
            var num2 = $(t).attr("Promotion-Num2");
            var num3 = $(t).attr("Promotion-Num3");
            var alerttype = $(t).attr("Promotion-T");
            var data;
            if (num < 0) return false;
            if (type == "f" && BENLAI.Model.CartModels.FullList.length > num) {
                data = BENLAI.Model.CartModels.FullList[num].HitBase;
                BENLAI.Model.CartTemp.SelectProduct = -1;
                BENLAI.Model.CartTemp.SelectCeng = BENLAI.Model.CartModels.FullList[num].HitBase.HitCeng;
                BENLAI.Model.CartTemp.SelectPromotionsSysNo = BENLAI.Model.CartModels.FullList[num].HitBase.PromotionsSysNo;
                BENLAI.Model.CartTemp.Path = type + "-" + BENLAI.Model.CartTemp.SelectPromotionsSysNo;
            }
            if (type == "s" && BENLAI.Model.CartModels.SingleList.length > num) {
                if (num2 < 0) return false;
                if (BENLAI.Model.CartModels.SingleList[num].HitBaseList.length > num2) {
                    data = BENLAI.Model.CartModels.SingleList[num].HitBaseList[num2];
                    BENLAI.Model.CartTemp.SelectProduct = BENLAI.Model.CartModels.SingleList[num].Product.ProductSysNo;
                    BENLAI.Model.CartTemp.SelectCeng = BENLAI.Model.CartModels.SingleList[num].HitBaseList[num2].HitCeng;
                    BENLAI.Model.CartTemp.SelectPromotionsSysNo = BENLAI.Model.CartModels.SingleList[num].HitBaseList[num2].PromotionsSysNo;
                    BENLAI.Model.CartTemp.Path = type + "-" + BENLAI.Model.CartTemp.SelectPromotionsSysNo + "-" + BENLAI.Model.CartTemp.SelectProduct;
                }
            }
            if (type == "mh" && BENLAI.Model.CartModels.MutiList.length > num) {
                if (num2 < 0) return false;
                if (BENLAI.Model.CartModels.MutiList[num].HitBaseList.length > num2) {
                    data = BENLAI.Model.CartModels.MutiList[num].HitBaseList[num2];
                    BENLAI.Model.CartTemp.SelectProduct = -1;
                    BENLAI.Model.CartTemp.SelectCeng = BENLAI.Model.CartModels.MutiList[num].HitBaseList[num2].HitCeng;
                    BENLAI.Model.CartTemp.SelectPromotionsSysNo = BENLAI.Model.CartModels.MutiList[num].HitBaseList[num2].PromotionsSysNo;
                    BENLAI.Model.CartTemp.Path = type + "-" + BENLAI.Model.CartTemp.SelectPromotionsSysNo;
                }
            }
            if (type == "md" && BENLAI.Model.CartModels.MutiList.length > num) {
                if (num2 < 0) return false;
                if (BENLAI.Model.CartModels.MutiList[num].ProductList.length > num2) {
                    if (num3 < 0) return false;
                    if (BENLAI.Model.CartModels.MutiList[num].ProductList[num2].HitBaseList.length > num3) {
                        data = BENLAI.Model.CartModels.MutiList[num].ProductList[num2].HitBaseList[num3];
                        BENLAI.Model.CartTemp.SelectProduct = BENLAI.Model.CartModels.MutiList[num].ProductList[num2].Product.ProductSysNo;
                        BENLAI.Model.CartTemp.SelectCeng = BENLAI.Model.CartModels.MutiList[num].ProductList[num2].HitBaseList[num3].HitCeng;
                        BENLAI.Model.CartTemp.SelectPromotionsSysNo = BENLAI.Model.CartModels.MutiList[num].ProductList[num2].HitBaseList[num3].PromotionsSysNo;
                        BENLAI.Model.CartTemp.Path = type + "-" + BENLAI.Model.CartTemp.SelectPromotionsSysNo + "-" + BENLAI.Model.CartTemp.SelectProduct;
                    }
                }
            }
            if (!data) return false;
            if (alerttype == 1) {
                this.AlertGift(data);
            } else if (alerttype == 2) {
                this.AlertAddPlus(data);
            }
        },
        AlertAddPlus: function (model) {
            if (model) {
                ShowBack();
                $('[alertType ="a"]').html('');
                $.BENLAI.tmpl({ dom: $('[alertType ="a"]'), v: BENLAI.Model.CartTemp.CartAddPlusAlert, datas: model });
                $('[alertType ="a"]').show();
            }
        },
        AlertGift: function (model) {
            if (model) {
                ShowBack();
                $('[alertType ="g"]').html('');
                $.BENLAI.tmpl({ dom: $('[alertType ="g"]'), v: BENLAI.Model.CartTemp.CartGiftAlert, datas: model });
                $('[alertType ="g"]').show();
            }
        },
        HideAddPlus: function (t, event) {
            $('[alertType ="a"]').hide();
            HideBack();
            $('[alertType ="a"]').html('');
        },
        HideGift: function (t, event) {
            $('[alertType ="g"]').hide();
            HideBack();
            $('[alertType ="g"]').html('');
        },
        InsertAddPlus: function (t, event) {
            var addPlus = $('[data-type="AddPlusInput"]');
            var Productid = 0;
            var qty = 0;
            var GiftNoNum = "";
            if (addPlus.length > 0) {
                addPlus.each(function (k, v) {
                    if ($(v).val() > 0) {
                        Productid = $(v).attr("Productid");
                        qty = $(v).val();
                    }
                });
            } else {
                addPlus = $('[BoxType="h"]:checked');
                if (addPlus.length > 0) {
                    Productid = addPlus.attr("Productid");
                    qty = 1;
                }
            }
            if (Productid > 0) GiftNoNum = Productid + "," + qty;
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/SetSelectGift',
                data: {
                    PromotionSysNo: BENLAI.Model.CartTemp.SelectPromotionsSysNo,
                    ProductSysNo: BENLAI.Model.CartTemp.SelectProduct,
                    Ceng: BENLAI.Model.CartTemp.SelectCeng,
                    Path: BENLAI.Model.CartTemp.Path,
                    GiftNoNum: GiftNoNum
                },
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            HideBack();
                            $.App.trigger('bind:cart');
                        } else if (result.Status == -1) {
                            if (result.data != null)
                                BENLAI.Model.CartModels = result.data;
                            HideBack();
                            $.App.trigger('bind:cart');
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        InsertGift: function (t, event) {
            var gift = $('[BoxType="g"]:checked');
            if (!gift) {
                alert("请选择赠品后再确定！");
                return false;
            }
            var Productid = gift.attr("Productid");
            var qty = gift.attr("qty");
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/SetSelectGift',
                data: {
                    PromotionSysNo: BENLAI.Model.CartTemp.SelectPromotionsSysNo,
                    ProductSysNo: BENLAI.Model.CartTemp.SelectProduct,
                    Ceng: BENLAI.Model.CartTemp.SelectCeng,
                    Path: BENLAI.Model.CartTemp.Path,
                    GiftNoNum: Productid + "," + qty
                },
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            HideBack();
                            $.App.trigger('bind:cart');
                        } else {
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        Pay: function (t, event) {
            var productId = $("[BoxType='p']:checked");
            if (!productId) {
                alert('请先选择您要结算的商品');
                return false;
            }
            if (BENLAI.Model.CartModels.IsAlertWindow == 1 && BENLAI.Model.CartTemp.IsSelectSplitOrder != 1) {
                this.ShowChildTan();
                return false;
            }

            try {

                //BI埋点
                var notChecked = $("[BoxType='p']:not([BoxType='p']:checked)");
                var checkedProduct = [], checkedSaleRule = [], uncheckedProduct = [], uncheckedSaleRule = [];
                productId.each(function() {
                    var productCheckbox = $(this),dataType=productCheckbox.attr('data-producttype'),productid=productCheckbox.attr('data-productid');
                    if (dataType == "0") {
                        checkedProduct.push(productid);
                    } else if (dataType == "1") {
                        checkedSaleRule.push(productid);
                    }
                });
                notChecked.each(function() {
                    var productCheckbox = $(this), dataType = productCheckbox.attr('data-producttype'), productid = productCheckbox.attr('data-productid');
                    if (dataType == "0") {
                        uncheckedProduct.push(productid);
                    } else if (dataType == "1") {
                        uncheckedSaleRule.push(productid);
                    }
                });
                
                BIStatic.pushForBalance(checkedProduct, uncheckedProduct, checkedSaleRule, uncheckedSaleRule);
            } catch (e) {

            } 
            debugger 
            $.BENLAI.ajax({
                type: 'POST',
                cache: false,
                notvalidate: true,
                url: '/Cart/CheckValidate',
                data: {
                    SelectType: $(".pop_select a.on").attr("data-id")
                },
                success: function (data) {
                    if (AjaxValidate(data)) {
                        if (data.status == -1) {
                            ShowLoginHeader(1);
                        } else if (data.status == 1) {
                            DSPGoForSubmitCart();
                            if (data.url)
                                window.location.href = data.url;
                            else
                                window.location.href = "/order.html";
                        } else if (data.status == 0) {
                            GetSimilarItem(data.msg);
                        } else if (data.status == -2) {
                            alert(data.msg)
                        }
                    }
                }
            });
        },
        BFD: function () {
            $('#right_cart').html(BENLAI.Model.CartModels.TotalCount);
            var keys = BENLAI.Model.CartModels.CartListBA;
            BFD_ITEM_INFO = {
                items: keys, // 2维数组，参数分别是['商品id号','购物车中该商品的数量','该商品的单价']
                user_id: BENLAI.Model.CartTemp.BaseUserId.toString(),  //  当前用户的user_id，string类型。注意：user_id不是用户的真实注册名，而是其注册名的编号,此用户包括注册用户以及匿名用户等所有用户；
                client: "Ctest_72", //这个帐号是百分点技术人员使用的帐号，请您不要修改这句代码！
                city: window.Cookies('DeliverySysNo').val() || 2
            };
            setTimeout(function () {
                var url = (('https:' == document.location.protocol ? 'https://ssl-static1' : 'http://static1') + '.bfdcdn.com/service/benlai/bl_cart.js');
                loadScript(url);
            }, 0);
        },
        Coudan: function (t, event) {
            BENLAI.Model.CartTemp.CouDanPriceLevel = $(t).attr("tippricelevel");
            BENLAI.Model.CartTemp.CouDanTitel = $(t).attr("tiptitle");
            BENLAI.Model.CartTemp.CouDanType = $(t).attr("tiptype");
            BENLAI.Model.CartTemp.CouDanPageIndex = 1;
            this.CoudanFun();
        },
        HideCoudan: function (t, event) {
            $('[alertType ="coudan"]').hide();
            HideBack();
            $('[alertType ="coudan"]').html('');
        },
        AddCoudan: function (t, event) {
            //凑单 确定
            var Products = "";
            $.each($('input[data-type="input1"]'), function (index, value) {
                var unitQU = Number($(value).val());
                var sysno = $(value).attr("sysno");
                if (unitQU >= 1) {
                    Products += sysno + "," + unitQU + ",0,1|";
                }
            });
            this.HideCoudan();
            $.BENLAI.ajax({
                type: 'POST',
                url: '/Cart/AddShoppingCart',
                data: {
                    products: Products,
                    Source: 'cart'
                },
                cache: false,
                success: function (result) {
                    if (AjaxValidate(result)) {
                        if (result.Status == 0) {
                            BENLAI.Model.CartModels = result.data;
                            if (result.errorlist) {
                                ShowCartMessage(result.errorlist);
                            }
                            $.App.trigger('bind:cart');
                        } else {
                            alert(result.Msg);
                        }
                    }
                }
            });
        },
        CoudanMinus: function (t, event) {
            var num = $(t).parent().parent().find("input").val();
            if (Number(num) <= 1)
                $(t).parent().parent().find("input").val(0);
            else
                $(t).parent().parent().find("input").val(Number(num) - 1);
            this.CoudanTotal();
        },
        CoudanAdd: function (t, event) {
            var num = $(t).parent().parent().find("input").val();
            if (Number(num) >= 99)
                $(t).parent().parent().find("input").val(99);
            else
                $(t).parent().parent().find("input").val(Number(num) + 1);
            this.CoudanTotal();
        },
        CoudanLeft: function (t, event) {
            BENLAI.Model.CartTemp.CouDanPageIndex = BENLAI.Model.CartTemp.CouDanPageIndex - 1;
            this.CoudanFun();
        },
        CoudanRight: function (t, event) {
            BENLAI.Model.CartTemp.CouDanPageIndex = BENLAI.Model.CartTemp.CouDanPageIndex + 1;
            this.CoudanFun();
        },
        CoudanFun: function () {
            $.BENLAI.ajax({
                type: 'POST',
                url: "/Cart/GetCouDanList",
                data: {
                    priceLevel: BENLAI.Model.CartTemp.CouDanPriceLevel,
                    type: BENLAI.Model.CartTemp.CouDanType,
                    pageindex: BENLAI.Model.CartTemp.CouDanPageIndex,
                    pagesize: 8
                },
                cache: false,
                success: function (data) {
                    if (AjaxValidate(data)) {
                        BENLAI.Model.CartTemp.CouDanPageIndex = data.data.PageIndex;
                        BENLAI.Model.CartTemp.CouDanTotalPage = data.data.TotalPage;
                        if (data.data.List.length > 0) {
                            $('[alertType ="coudan"]').html('');
                            $.BENLAI.tmpl({ dom: $('[alertType ="coudan"]'), v: BENLAI.Model.CartTemp.CartCoudan, datas: data.data });
                            $('[alertType ="coudan"]').show();
                            $('[data-type="coudanTitle"]').html($('#coudanTitle').val());
                            ShowBack();
                        }
                    }
                    return false;
                }
            });
        },
        CoudanTotal: function () {
            var inputs = $('input[data-type="input1"]');
            var quanlity = 0;
            var totalPrice = 0;
            var unitQU = 0;
            var unitPrice = 0;
            $.each(inputs, function (index, value) {
                unitQU = Number($(inputs[index]).val());
                unitPrice = parseFloat($(inputs[index]).attr("price")).toFixed(2);
                quanlity += unitQU;
                totalPrice += unitQU * unitPrice;

            });
            $(".pop_total").html('已选择<font>' + quanlity + '</font>件商品，金额（不含运费）= <span>¥ ' + totalPrice.toFixed(2) + '</span>');
        },
        ShowChildTan: function () {
            $('[alertType ="ChildTan"]').html('');
            if (BENLAI.Model.CartModels.AlertWindowType == 1) {
                $.BENLAI.tmpl({ dom: $('[alertType ="ChildTan"]'), v: BENLAI.Model.CartTemp.OverSeaTip, datas: BENLAI.Model.CartModels });
            }
            else if (BENLAI.Model.CartModels.AlertWindowType == 2) {
                $.BENLAI.tmpl({ dom: $('[alertType ="ChildTan"]'), v: BENLAI.Model.CartTemp.SplitOrderTip, datas: BENLAI.Model.CartModels });
            }
            ShowBack();
            $('[alertType ="ChildTan"]').show();
        },
        HideChildTan: function () {
            $('[alertType ="ChildTan"]').html('');
            $('[alertType ="ChildTan"]').hide();
            HideBack();
        },
        ChildSelect: function (t, event) {
            $(".pop_select a").removeClass("on");
            $(t).addClass("on");
        },
        SelectOkChildTan: function () {
            BENLAI.Model.CartTemp.IsSelectSplitOrder = 1;
            this.Pay();
        },
        init: function () {
            BENLAI.Model.CartTemp.BaseUserId = BENLAI.Model.CartModels.CustomerSysNo == -999999 ? "" : BENLAI.Model.CartModels.CustomerSysNo;
            BENLAI.Model.CartTemp.CartTemps = $("#CartContent").val();
            BENLAI.Model.CartTemp.CartAddPlusAlert = $("#AddPlusContent").val();
            BENLAI.Model.CartTemp.CartGiftAlert = $("#GiftContent").val();
            BENLAI.Model.CartTemp.CartCoudan = $("#CoudanContent").val();
            BENLAI.Model.CartTemp.OverSeaTip = $("#OverSeaTip").val();
            BENLAI.Model.CartTemp.SplitOrderTip = $("#SplitOrderTip").val();
            this.bind.apply(this, arguments);
            this.BFD();
            BENLAI.Cart.TuiJian();
        }
    });
});
BENLAI.Cart = {
    TuiJian: function () {
        $('[data-type="tuijian"]').CreateController({
            appEvents: {
                'load:addplus': 'LoadTabAddPlus'
            },
            events: {
                '#tablist a click': 'TabClick',
                '#tablist a mouseover': 'TabMouseOn',
                '#tablist a mouseleave': 'TabMouseLeave'
            },
            TabClick: function (t, event) {
                var num = $(t).attr("num");
                this.TabRunTurn(num);
            },
            TabMouseOn: function (t, event) {
                var that = this;
                var num = $(t).attr("num");
                BENLAI.Model.CartTemp.MouseTab = setTimeout(function () {
                    that.TabRunTurn(num);
                }, 400);
            },
            TabMouseLeave: function (t, event) {
                clearInterval(BENLAI.Model.CartTemp.MouseTab);
            },
            TabRunTurn: function (num) {
                $('#tablist a').removeClass("on");
                $('#tablist a[num="' + num + '"]').addClass("on");
                $('[data-type="tabdiv"]').hide();
                $('[data-type="tabdiv"][num="' + num + '"]').show();
                var that = this;
                switch (Number(num)) {
                    case 1: that.LoadTabAddPlus(); break;
                    case 2: that.GetTabProduct(2, "暂无每日最新鲜", "/Shopping/geteverydayfresh"); break;
                    case 3: break;
                    case 4: that.GetTabProduct(4, "暂无浏览记录", "/Shopping/getcartbrowserproductlist"); break;
                    case 5: that.GetTabProduct(5, "暂无收藏信息", "/Shopping/getcustomerwish"); break;
                    case 6: that.ShowDeletedProductInfo(); break;
                    default: break;
                }
            },
            LoadTabAddPlus: function () {
                var that = this;
                if ($('#isFirst').val() != "1") {
                    $.ajax({
                        type: 'POST',
                        url: '/Cart/TabAddPlus',
                        cache: false,
                        success: function (result) {
                            if (result != "" && result != null && result.length > 0 && result != "\r\n") {
                                $("#tabdiv1").html("");
                                $("#tabdiv1").html(result);
                            } else {
                                $("#tabdiv1").html("");
                                var num = $('#tablist a:visible').eq(1).attr("num");
                                that.TabRunTurn(num);
                            }
                        }
                    });
                } else {
                    $('#isFirst').val(2);
                }
            },
            ShowDeletedProductInfo: function () {
                var website = window.Cookies('WebSiteSysNo').val();
                var deleteProduct = window.Cookies('deleteCartProducts' + website).val();
                if (BENLAI.Model.CartTemp.DeleteProduct != deleteProduct) {
                    BENLAI.Model.CartTemp.DeleteProduct = deleteProduct;
                    $.BENLAI.ajax({
                        type: 'POST',
                        url: "/Shopping/AllDeletedProducts",
                        notvalidate: true,
                        cache: false,
                        success: function (data) {
                            $('[data-type="tabdiv"][num="6"]').html("");
                            $('[data-type="tabdiv"][num="6"]').html(data);
                            return false;
                        }
                    });
                } else if (deleteProduct == null || deleteProduct == "") {
                    $('[data-type="tabdiv"][num="6"]').html(BENLAI.Model.CartTemp.NoProductMsg.replace("{0}", "暂无删除记录"));
                }
            },
            GetTabProduct: function (num, writer, url) {
                var htmlId = '[data-type="tabdiv"][num="' + num + '"]';
                var index = $(htmlId).html().indexOf("正在加载");
                var index1 = $(htmlId).html().indexOf(writer);
                var NoMsg = BENLAI.Model.CartTemp.NoProductMsg.replace("{0}", writer);
                if (index >= 0 || index1 >= 0 || $(htmlId).html().length > 100) {
                    return false;
                } else {
                    $(htmlId).html(BENLAI.Model.CartTemp.LoadingMsg);
                }
                $.ajax({
                    type: "post",
                    async: true,
                    cache: false,
                    url: url,
                    success: function (data) {
                        if (AjaxValidate(data)) {
                            if (data.length > 0) {
                                $.BENLAI.tmpl({ dom: $(htmlId), v: $("#TabProduct").val(), datas: data });
                                lazyLoad.Run();
                                for (var i = 0; i < data.length; i++) {
                                    var info = data[i];
                                    var sysNo = info.SysNo;
                                    var butn = $(".hotid[value=" + sysNo + "]").siblings(".butn");
                                    if (!info.IsCanDelivery) {
                                        butn.html('<input type="button" value="" class="butn3_4 fl" />');
                                    } else if (!info.Inventory) {
                                        butn.html('<input type="button" value="" class="butn1_3 fl" onclick="NotifyAdding(' + sysNo + ', 1)" />');
                                    } else {
                                        butn.html('<input type="button" class="butn3" value="" data-type="add" data-productid="' + sysNo + '" data-producttype="0" name="btnbutton" id="btnRecommentList' + sysNo + '" />');
                                    }
                                }

                            } else {
                                $(htmlId).html(NoMsg)
                            }
                        }
                    },
                    error: function () {
                        $(htmlId).html(NoMsg)
                    }
                })
            },
            init: function () {
                var num = $('#tablist a:visible').eq(0).attr("num");
                this.TabRunTurn(num);
                if (alertPriceChange != "0") {
                    var n = alertPriceChange;
                    alertPriceChange = "0";
                    alert("本姑娘温馨提示：您选购的商品中有" + n + "件发生价格变化，如您确认购买该商品，请再次结算。谢谢！");
                }
                if (alertOrderTypeSelectError == "1") {
                    alertPriceChange = "0";
                    alert("您选择的结算订单类型错误，请重新去结算！");
                }
            }
        });
    }
}
BENLAI.Model.CartTemp = {
    LoadingMsg: '<div class="zt_02 tac"><img src="' + window.ImageUrl + '/Content/images/loading.gif" /> 正在加载数据，请稍候......</div>',
    NoProductMsg: '<div class="mb10 mt10 tac" style="padding-top: 10px; text-align: center; height: 200px;">{0}</div>'
};

function uptRightCart(r) {

    try {
        var productList = "";//for dsp
        var i = 0;
        var prducts = r.SProduct;
        var count = 0;
        while (i < prducts.length) {
            var prodTempI = prducts[i];
            count += prodTempI.Quantity;
            i++;
            productList += prodTempI.ProductSysNo + "," + prodTempI.Quantity + ";";
        }


        if (r.MutiList != undefined) {
            var j = 0;
            while (j < r.MutiList.length) {

                if (r.MutiList[j] != undefined) {

                    var k = 0;
                    while (k < r.MutiList[j].ProductList.length) {

                        if (r.MutiList[j].ProductList[k] != undefined) {
                            count += r.MutiList[j].ProductList[k].Product.Quantity
                        }
                        k++;
                    }
                }
                j++;
            }


        }


        if (count >= 0) {
            $("#right_cart").html(count);
        }
        //dsp
        var money = r.TotalAmt;
        DSPGoForCart(money, productList);
    } catch (e) {

    }

} $(function () { uptRightCart(BENLAI.Model.CartModels); })
